//
//  WPReplacePhoneNumVC.m
//  wobingwoyi
//
//  Created by WGP on 16/8/4.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPReplacePhoneNumVC.h"
#import "WLCaptcheButton.h"
#import "NSString+WPSizeOfString.h"
#import "WPMineLoginVC.h"

@interface WPReplacePhoneNumVC ()

@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UIButton *doneBtn;
@property (strong, nonatomic) UILabel *oldPhoneNumLabel;
@property (strong, nonatomic) UITextField *nowPhoneNumField;
@property (strong, nonatomic)  UITextField *getVerifyCodeField;
@property(nonatomic,strong)WLCaptcheButton *getVerifyCodeBtn;;
@property(nonatomic,assign)BOOL isSended;

@end

@implementation WPReplacePhoneNumVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [btn sizeToFit];
    [btn addTarget:self action:@selector(backBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacer.width = -8;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_left, nil];
    
    self.view.backgroundColor  =GlobalBgColor;
    self.title = @"更绑定手机号";
    
    [self setupUI];
    
     WPUserAccount *userAccount = [WPUserAccountViewModel sharedInstance].userAccount;
    if (userAccount.user.phone.length)
    {
        self.oldPhoneNumLabel.text = [NSString stringWithFormat:@"当前手机号:  %@",userAccount.user.phone];
    }
}

-(void)setupUI
{
    [self bgView];
    [self doneBtn];
}

-(UIView *)bgView
{
    if (_bgView == nil)
    {
        _bgView = [UIView new];
        _bgView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_bgView];
        
        [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.top.equalTo(self.view).offset(10 + 64);
            make.height.mas_equalTo(132);
        }];
        
        self.oldPhoneNumLabel = [UILabel new];
        self.oldPhoneNumLabel.textAlignment = NSTextAlignmentLeft;
        self.oldPhoneNumLabel.textColor = GLobalFontColor;
        self.oldPhoneNumLabel.font = [UIFont systemFontOfSize:14];
        [_bgView addSubview:self.oldPhoneNumLabel];
        [self.oldPhoneNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bgView).offset(15);
            make.top.right.equalTo(_bgView);
            make.height.mas_equalTo(44);
        }];
        
        self.nowPhoneNumField = [UITextField new];
        self.nowPhoneNumField.placeholder = @"请输入新的手机号码";
        self.nowPhoneNumField.textColor = GLobalFontColor;
        self.nowPhoneNumField.font = [UIFont systemFontOfSize:14];
        [_bgView addSubview:self.nowPhoneNumField];
        [self.nowPhoneNumField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.height.equalTo(self.oldPhoneNumLabel);
            make.bottom.equalTo(_bgView);
        }];
        
        WLCaptcheButton *getVerificationCodeBtn = [WLCaptcheButton new];
        self.getVerifyCodeBtn = getVerificationCodeBtn;
        getVerificationCodeBtn.identifyKey = @"WPReplacePhoneNumVC";
        [getVerificationCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        getVerificationCodeBtn.disabledTitleColor = [UIColor lightGrayColor];
        [getVerificationCodeBtn setTitleColor:GlobalColor forState:UIControlStateNormal];
        getVerificationCodeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        //    [getVerificationCodeBtn sizeToFit];
        [getVerificationCodeBtn addTarget:self action:@selector(sendVerifyCodeBtn:) forControlEvents:UIControlEventTouchDown];
        [_bgView addSubview:getVerificationCodeBtn];
        
        CGSize size = [getVerificationCodeBtn.titleLabel.text sizeWithMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:14];
        [getVerificationCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_bgView);
            make.right.equalTo(_bgView).offset(-10);
            make.height.mas_equalTo(43);
            make.width.mas_equalTo(size.width + 2);
        }];
        
        self.getVerifyCodeField = [UITextField new];
        self.getVerifyCodeField.placeholder = @"验证码";
        self.getVerifyCodeField.textColor = GLobalFontColor;
        self.getVerifyCodeField.font = [UIFont systemFontOfSize:14];
        [_bgView addSubview:self.getVerifyCodeField];
        [self.getVerifyCodeField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bgView).offset(15);
            make.centerY.equalTo(_bgView);
            make.right.equalTo(self.getVerifyCodeBtn.mas_left).offset(-10);
            make.height.mas_equalTo(43);
        }];
        
        UIImageView *line1 = [UIImageView lineImageView];
        UIImageView *line2 = [UIImageView lineImageView];
        UIImageView *line3 = [UIImageView lineImageView];
        UIImageView *line4 = [UIImageView lineImageView];
        UIImageView *line5 = [UIImageView lineImageView];
        [_bgView addSubview:line1];
        [_bgView addSubview:line2];
        [_bgView addSubview:line3];
        [_bgView addSubview:line4];
        [_bgView addSubview:line5];
        
        line4.frame = CGRectMake(0, 132, SCREEN_WIDTH, 0.5);
        line3.frame = CGRectMake(15, 88, SCREEN_WIDTH-15, 0.5);
        line2.frame = CGRectMake(15, 44, SCREEN_WIDTH-15, 0.5);
        line1.frame = CGRectMake(0, 0, SCREEN_WIDTH, 0.5);
        
        [line5 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(0.5);
            make.right.equalTo(getVerificationCodeBtn.mas_left).offset(-10);
            make.centerY.equalTo(getVerificationCodeBtn);
            make.height.mas_equalTo(24);
        }];
    }
    return _bgView;
}

-(UIButton *)doneBtn
{
    if (_doneBtn == nil)
    {
        _doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneBtn setBackgroundImage:[UIImage imageNamed:@"normal"] forState:UIControlStateNormal];
        [_doneBtn setBackgroundImage:[UIImage imageNamed:@"highLight"] forState:UIControlStateHighlighted];
        [_doneBtn setTitle:@"绑定" forState:UIControlStateNormal];
        [_doneBtn addTarget:self action:@selector(doneBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_doneBtn];
        
        [_doneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(20);
            make.right.equalTo(self.view).offset(-20);
            make.height.mas_equalTo(44);
            make.top.equalTo(self.bgView.mas_bottom).offset(80);
        }];
    }
    return _doneBtn;
}

- (void)sendVerifyCodeBtn:(WLCaptcheButton *)sender
{
    WPUserAccount *userAccount = [WPUserAccountViewModel sharedInstance].userAccount;
    
    NSString *url = @"user/sendMessage.do";
    NSDictionary *parameters = @{@"telephone":userAccount.user.phone};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self showSuccessInfoWithStatus:@"验证码已发送至手机"];
        [sender fire];
        self.isSended = YES;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self showErrorInfoWithStatus:@"网络错误"];
            self.isSended = NO;
    }];
}


-(BOOL)isLegalPhoneNum
{
    if (![NSString isMobile:self.nowPhoneNumField.text])
    {
        return NO;
    }
    return YES;
}

- (void)doneBtnDidClick:(UIButton *)sender
{
    if (!self.getVerifyCodeField.text.length)
    {
        [self showErrorInfoWithStatus:@"请输入验证码"];
        return;
    }
    
    if (!(self.nowPhoneNumField.text.length && [NSString isMobile:self.nowPhoneNumField.text]))
    {
        [self showErrorInfoWithStatus:@"手机号码格式不正确"];
        return ;
    }
    
    NSString *url = @"user/changeBindTel.do";
    
    NSDictionary *dict = @{@"telephone":self.nowPhoneNumField.text,@"codeInput":self.getVerifyCodeField.text};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = (NSDictionary *)responseObject;
        if ([dict[@"result"] isEqualToString:@"success"])
        {
            WPUserAccount *userAccount = [WPUserAccountViewModel sharedInstance].userAccount;
            userAccount.user.phone = self.nowPhoneNumField.text;
            [userAccount saveUserAccount];
            userAccount = nil;
            
            [self.navigationController popViewControllerAnimated:YES];
            [self showSuccessInfoWithStatus:@"更绑成功"];
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else if([responseObject[@"detail"] isEqualToString:@"areadyBind"])
            {
                [self showErrorInfoWithStatus:@"该手机号已绑定"];
            }
            else
            {
                [self showErrorInfoWithStatus:@"更绑失败"];
            }

        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
        
    }];
}

//重新登陆的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
        WPMineLoginVC *vc = [WPMineLoginVC new];
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
}

- (void)backBtnDidClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
